package shop.core.common.filter;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shop.core.common.bean.ManageContainer;
import shop.core.common.oscache.SystemManager;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


/**
 * 用户登录过滤器
 *
 * @author huangf
 */
public class LoginFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    protected FilterConfig filterConfig;

    public void init(FilterConfig arg0) throws ServletException {
        filterConfig = arg0;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        canMap.put("manageLogin", "/rest/manage/user/login");
        canMap.put("weightrecordInsert", "/rest/manage/weightrecord/insertJson");
        canMap.put("cartInsert", "/rest/manage/cart/insertJson");

        canMap.put("uploadImg", "/rest/manage/ued/config");
        canMap.put("wxmsg", "/rest/manage/wxmsg/connect");

        canMap.put("userToWx", "/rest/front/user/toWx");
        canMap.put("userCallBack", "/rest/front/user/callBack");

        if (canPass(req.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        if (req.getRequestURI().startsWith("/rest/manage") && req.getSession().getAttribute("userMenus") == null) {
            req.getSession().setAttribute(ManageContainer.manage_session_user_info, null);
            HttpServletResponse res = (HttpServletResponse) response;
            String url = req.getRequestURL().toString();
            String f = url.substring(0, url.indexOf(req.getContextPath()));
            String p = f + req.getContextPath() + "/rest/manage/user/login";
            logger.debug("过滤器" + req.getServletPath());
            res.sendRedirect(p);
            return;
        }

        String env = SystemManager.getInstance().getProperty("env");
        if (req.getRequestURI().startsWith("/rest/front") && req.getSession().getAttribute("userInfo") == null && env.equals("pro")) {
            HttpServletResponse res = (HttpServletResponse) response;
            String pid = req.getParameter("pid");
            String id = req.getParameter("id");
            String url = req.getRequestURL().toString();
            String f = url.substring(0, url.indexOf(req.getContextPath()));
            String p = "";
            if (!StringUtils.isBlank(pid)) {
                p = f + req.getContextPath() + "/rest/front/user/toWx" + "?pid=" + pid;
            } else if(!StringUtils.isBlank(id)){
                p = f + req.getContextPath() + "/rest/front/user/toWx"+"?id=" + id;
            }else{
                p = f + req.getContextPath() + "/rest/front/user/toWx";
            }
            res.sendRedirect(p);
            logger.debug("过滤器返回url"+p);
            return;
        }
        chain.doFilter(request, response);
    }


    // 可以通过的URL集合
    static Map<String, String> canMap = new HashMap<String, String>();

    /**
     * 能否通过
     *
     * @param servletPath
     * @return true:可以通过;false:不能通过
     */
    private boolean canPass(String servletPath) {
        for (Iterator<Entry<String, String>> it = canMap.entrySet().iterator(); it
                .hasNext(); ) {
            Entry<String, String> entry = it.next();
            if (servletPath.indexOf(entry.getValue()) != -1) {
                return true;
            }
        }
        return false;
    }

    public void destroy() {

    }
}
